package com.py.credit.ai.client;

import java.util.HashMap;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baidu.aip.face.AipFace;
import com.google.common.collect.Maps;
import com.py.credit.ai.constant.AipFaceConstant;
import com.py.credit.common.logs.DebugLogger;

@Component
public class AipFaceAdapter implements IAipFace {

	@Autowired
	AipFace client;

	@Override
	public JSONObject getUser(String userId, String groupId) {

		return client.getUser(userId, groupId, new HashMap<>());
	}

	@Override
	public JSONObject addUser(String image, String imageType, String groupId, String userId, String userInfo) {

		HashMap<String, String> options = Maps.newHashMapWithExpectedSize(1);
		options.put("user_info", userInfo);

		return client.addUser(image, imageType, groupId, userId, options);

	}

	@Override
	public Boolean verifyUser(String image, String imageType, String groupIdList, String userId) {

		boolean pass = false;
		HashMap<String, String> options = Maps.newHashMapWithExpectedSize(1);
		options.put("user_id", userId);
		JSONObject data = client.search(image, imageType, groupIdList, options);
		DebugLogger.debug(data);
		if (data.getInt("error_code") == 0) {

			double score = data.getJSONObject("result").getJSONArray("user_list").getJSONObject(0).getDouble("score");

			if (score > AipFaceConstant.SCORE_THRESHOLD) {

				pass = true;

			}

		}
		return pass;

	}

	@Override
	public JSONObject updateUser(String image, String imageType, String groupId, String userId) {

		return client.updateUser(image, imageType, groupId, userId, new HashMap<>());
	}

	@Override
	public JSONObject deleteUser(String userId, String groupId) {

		return client.deleteUser(groupId, userId, new HashMap<>());
	}

	@Override
	public JSONObject deleteFace(String userId, String groupId, String faceToken) {

		return client.faceDelete(groupId, userId, faceToken, new HashMap<>());
	}

	@Override
	public JSONObject getFaceList(String userId, String groupId) {

		return client.faceGetlist(userId, groupId, new HashMap<>());
	}

	@Override
	public JSONObject getGroupUsers(String groupId) {

		return client.getGroupUsers(groupId, new HashMap<>());
	}

	@Override
	public JSONObject getGroupList() {

		return client.getGroupList(new HashMap<>());
	}

	@Override
	public Boolean detect(String image, String imageType) {

		boolean pass = false;

		JSONObject data = client.detect(image, imageType, new HashMap<>());

		DebugLogger.debug("人脸检验结果:" + data);

		if (data.getInt("error_code") == 0) {

			pass = true;

		}
		return pass;

	}

}
